package com.ice.framework.common.util;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.lang.copier.Copier;
import com.ice.framework.common.entity.ParallelResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 并行工具
 * @author wangwei
 * @Date 2022/12/2 10:57
 */

public class ParallelUtil {

    private static final Logger logger = LoggerFactory.getLogger(ParallelUtil.class);

    /**
     * 并行执行工具
     * 多个任务执行，并返回
     * ParallelUtil.executeParallelTask(()->{
     *
     * })
     *
     * @Author wangwei
     * @Date 2022/12/2
     */
    public static List<ParallelResult<Object>> executeParallelTask(List<Callable<ParallelResult<Object>>> tasks, ExecutorService executorService, long timeOut) {
        List<ParallelResult<Object>> resultList = new ArrayList<>();
        ExecutorCompletionService<ParallelResult<Object>> completionService = new ExecutorCompletionService<>(executorService);
        for (Callable<ParallelResult<Object>> task : tasks) {
            completionService.submit(task);
        }
        try {
            //遍历获取结果
            for (int i = 0; i < tasks.size(); i++) {
                Future<ParallelResult<Object>> parallelResultFuture = completionService.poll(timeOut, TimeUnit.SECONDS);
                resultList.add(parallelResultFuture.get());
            }
        } catch (InterruptedException | ExecutionException e) {
            logger.error("并行工具异常：{}", ExceptionUtil.stacktraceToString(e));
        }
        return resultList;
    }
}
